//
//  customKeyboard.m
//  Etion
//
//  Created by  user on 11-4-14.
//  Copyright 2011 GuangZhouXuanWu. All rights reserved.
//

#import "XUINumberKeyboard.h"

#import "UITextFieldExtend.h"

#import "UIImageExtend.h"

#define XUINumberKeyboardNum(n)      100+n
#define XUINumberKeyboardPoint       110
#define XUINumberKeyboardClear       120
#define XUINumberKeyboardDelete      130
#define XUINumberKeyboardClose       140

#define  NumberTextFieldEditingChanged 1<<20

@protocol XUINumberKeyboardDelegate <NSObject>

- (UITextField*)textField;

@end

@interface XUINumberKeyboard : UIView
{
    UIView *_customKeyboardView;
}

@property(nonatomic,assign) id<XUINumberKeyboardDelegate> delegate;

@end

@implementation XUINumberKeyboard

-(id)init
{
    self = [super initWithFrame:CGRectZero];
    
    [self createCustomNumberkeyBoardPanel];
    
    return self;
}

- (void)dealloc
{
    [_customKeyboardView release_mm];
    superdealloc_mm;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    self.frame = self.superview.bounds;
    
    [self configCustomNumberKeyBoardPanel];
}

- (void)createCustomNumberkeyBoardPanel
{
    if (_customKeyboardView == nil)
    {
        _customKeyboardView = [[UIView alloc] initWithFrame:self.bounds];
        _customKeyboardView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _customKeyboardView.backgroundColor = [UIColor colorWithHex:0xdcdee1];
        [self addSubview:_customKeyboardView];
        
        for (NSInteger i = 0; i < 12; i ++)
        {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.tag = XUINumberKeyboardNum(i);
            [btn setBackgroundImage:[[UIImage imageWithMainBundle:@"nkb_btnbg_white"] resizeableCenterImage] forState:UIControlStateNormal];
            [btn setTitle:[NSString stringWithFormat:@"%@", @(i + 1)] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [btn addTarget:self action:@selector(clickedAtIndexButton:) forControlEvents:UIControlEventTouchUpInside];
            [_customKeyboardView addSubview:btn];
            
            if (i == 9) //负号
            {
                [btn setTitle:@"-" forState:UIControlStateNormal];
            }
            else if (i == 10) //zero btn
            {
                [btn setTitle:@"0" forState:UIControlStateNormal];
            }
            else if (i == 11) //point btn
            {
                [btn setTitle:@"." forState:UIControlStateNormal];
            }
        }
        
        UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn1 setBackgroundImage:[[UIImage imageWithMainBundle:@"nkb_btnbg_gray"] resizeableCenterImage] forState:UIControlStateNormal];
        [btn1 setImage:[UIImage imageWithMainBundle:@"nkb_deletechar"] forState:UIControlStateNormal];
        [btn1 addTarget:self action:@selector(clickedDeleteCharButton:) forControlEvents:UIControlEventTouchUpInside];
        btn1.tag = XUINumberKeyboardDelete;
        [_customKeyboardView addSubview:btn1];
        
        UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn2 setBackgroundImage:[[UIImage imageWithMainBundle:@"nkb_btnbg_gray"] resizeableCenterImage] forState:UIControlStateNormal];
        [btn2 setImage:[UIImage imageWithMainBundle:@"nkb_clearall"] forState:UIControlStateNormal];
        [btn2 addTarget:self action:@selector(clearnAllChar) forControlEvents:UIControlEventTouchUpInside];
        btn2.tag = XUINumberKeyboardClear;
        [_customKeyboardView addSubview:btn2];
        
        UIButton *btn3 = [UIButton buttonWithType:UIButtonTypeCustom];
        btn3.titleLabel.font = [UIFont systemFontOfSize:12];
        [btn3 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn3 setBackgroundImage:[[UIImage imageWithMainBundle:@"nkb_btnbg_gray"] resizeableCenterImage] forState:UIControlStateNormal];
        [btn3 setImage:[UIImage imageWithMainBundle:@"nkb_hidekeyboard"] forState:UIControlStateNormal];
        [btn3 addTarget:self action:@selector(clickedHiddenKeyboardButton:) forControlEvents:UIControlEventTouchUpInside];
        btn3.tag = XUINumberKeyboardClose;
        [_customKeyboardView addSubview:btn3];
    }
}

-(void)configCustomNumberKeyBoardPanel
{
    if (_customKeyboardView != nil)
    {
        UIButton *minusBtn = nil;
        UIButton *zeroBtn = nil;
        UIButton *pointBtn = nil;
        
        _customKeyboardView.frame = self.bounds;
        
        CGFloat margin = 7;
        
        CGFloat rightOperationBtnW = (_customKeyboardView.width - 3 * margin ) / 6;
        CGFloat numberBtnW = (_customKeyboardView.width - 5 * margin - rightOperationBtnW ) / 3;
        CGFloat numberBtnH = (_customKeyboardView.height - 5 * margin ) / 4;
        
        for (NSInteger i = 0; i < 12; i ++)
        {
            UIButton *btn = (UIButton *)[_customKeyboardView viewWithTag:XUINumberKeyboardNum(i)];
            btn.frame = CGRectMake(margin + ( margin + numberBtnW ) * ( i % 3), margin + ( margin + numberBtnH ) * ( i / 3), numberBtnW, numberBtnH);
            if (i == 9)
            {
                minusBtn = btn;
            }
            else if (i == 10)
            {
                zeroBtn = btn;
            }
            else if (i == 11)
            {
                pointBtn = btn;
            }
        }
        
        UIButton *btn1 = (UIButton *)[_customKeyboardView viewWithTag:XUINumberKeyboardDelete];
        btn1.frame = CGRectMake(_customKeyboardView.width - margin - rightOperationBtnW, margin, rightOperationBtnW, numberBtnH);
        
        UIButton *btn2 = (UIButton *)[_customKeyboardView viewWithTag:XUINumberKeyboardClear];
        btn2.frame = CGRectMake(_customKeyboardView.width - margin - rightOperationBtnW, 2 * margin+numberBtnH, rightOperationBtnW, numberBtnH);
        
        UIButton *btn3 = (UIButton *)[_customKeyboardView viewWithTag:XUINumberKeyboardClose];
        btn3.frame = CGRectMake(_customKeyboardView.width - margin - rightOperationBtnW, 3 * margin + 2 * numberBtnH, rightOperationBtnW, 2 * numberBtnH+margin);
        
        XUINumberKeyboardType keyboardType = self.delegate.textField.keyboardType;
        
        if(keyboardType == XUINumberKeyboardTypeNumber)
        {
            pointBtn.hidden = NO;
            minusBtn.hidden = YES;
            zeroBtn.frame = CGRectMake(margin, zeroBtn.top, numberBtnW*2+margin, zeroBtn.height);
        }
        else if(keyboardType == XUINumberKeyboardTypeDecimal)
        {
            pointBtn.hidden = NO;
            minusBtn.hidden = YES;
            zeroBtn.frame = CGRectMake(margin, zeroBtn.top, numberBtnW*2+margin, zeroBtn.height);
        }
        else if(keyboardType == XUINumberKeyboardTypeInteger)
        {
            pointBtn.hidden = YES;
            minusBtn.hidden = YES;
            zeroBtn.frame = CGRectMake(margin, zeroBtn.top, numberBtnW*3+margin*2, zeroBtn.height);
        }
        else if(keyboardType == XUINumberKeyboardTypeFax || keyboardType == XUINumberKeyboardTypeSignInteger)
        {
            pointBtn.hidden = YES;
            minusBtn.hidden = NO;
            zeroBtn.frame = CGRectMake(numberBtnW+margin*2, zeroBtn.top, numberBtnW*2+margin, zeroBtn.height);
        }
        else if(keyboardType == XUINumberKeyboardTypeSignDecimal)
        {
            pointBtn.hidden = NO;
            minusBtn.hidden = NO;
            zeroBtn.frame = CGRectMake(numberBtnW+margin*2, zeroBtn.top, numberBtnW, zeroBtn.height);
        }
        
        if (self.delegate.textField.returnKeyType == UIReturnKeyNext)
        {
            [btn3 setTitle:@"下一项" forState:UIControlStateNormal];
            [btn3 setImage:nil forState:UIControlStateNormal];
        }
        else
        {
            [btn3 setTitle:@"" forState:UIControlStateNormal];
            [btn3 setImage:[UIImage imageWithMainBundle:@"nkb_hidekeyboard"] forState:UIControlStateNormal];
        }
    }
}

- (void)setTextFieldText:(NSString *)szText selectedRange:(NSRange)selectedRange
{
    UITextField *textField = self.delegate.textField;

    [textField setText:szText];
    
    [textField setSelectedRange:selectedRange];
    
    UIControlEvents e = [textField allControlEvents];
    if (e > 0 && (e & UIControlEventEditingChanged) == UIControlEventEditingChanged)
    {
        [[textField allTargets] enumerateObjectsUsingBlock:^(id obj, BOOL *stop)
        {
            NSArray *ar = [textField actionsForTarget:obj forControlEvent:e];
            for (NSString *s in ar)
            {
                [obj performSelector:NSSelectorFromString(s) withObject:textField];
            }
        }];
    }
}

- (void)clickedAtIndexButton:(id)sender
{
    NSString *str = [((UIButton *) sender) titleForState:UIControlStateNormal];
 
    UITextField *textField = self.delegate.textField;
    
    if ([textField.delegate respondsToSelector:@selector(textField:shouldChangeCharactersInRange:replacementString:)] == YES)
    {
        BOOL b = [textField.delegate textField:textField shouldChangeCharactersInRange:textField.selectedRange replacementString:str];
        if (b == NO)
            return;
    }
    
    if (NSOrderedSame == [str compare:@"."])
    {
        NSRange rang = [textField.text rangeOfString:@"."];
        if (rang.location == NSNotFound)
        {
            NSRange range = textField.selectedRange;
            NSString *newStr = [textField.text stringByReplacingCharactersInRange:range withString:str];
            [self setTextFieldText:newStr selectedRange:NSMakeRange(range.location + 1, 0)];
        }
    }
    else
    {
        NSRange range = textField.selectedRange;
        NSString *newStr = [textField.text stringByReplacingCharactersInRange:range withString:str];
        [self setTextFieldText:newStr selectedRange:NSMakeRange(range.location + 1, 0)];
    }
}


- (void)clickedDeleteCharButton:(id)sender
{
    UITextField *textField = self.delegate.textField;
    
    NSRange range = textField.selectedRange;
    if(range.length <= 0)
    {
        if(range.location >= 1)
            range = NSMakeRange(range.location - 1, 1);
        else
            range = NSMakeRange(0, 0);
    }
    NSString *newStr = [textField.text stringByReplacingCharactersInRange:range withString:@""];
    range.length = 0;
    [self setTextFieldText:newStr selectedRange:range];
}
 
- (void)clearnAllChar
{
    [self setTextFieldText:@"" selectedRange:NSMakeRange(0, 0)];
}

- (void)clickedHiddenKeyboardButton:(id)sender
{
    UITextField *textField = self.delegate.textField;
    
    if ([textField.delegate respondsToSelector:@selector(textFieldShouldReturn:)]==YES)
    {
        if ([textField.delegate textFieldShouldReturn:textField] == NO)
        {
            return;
        }
    }
    
    [textField resignFirstResponder];
}

static XUINumberKeyboard *s_numberKeyboard;

+ (XUINumberKeyboard*)numberKeyboard
{
    if(s_numberKeyboard == nil)
        s_numberKeyboard = [XUINumberKeyboard new];
    return s_numberKeyboard;
}

+ (void)loadNumberKeyboardWtihParentView:(id<XUINumberKeyboardDelegate>)parentView
{
    XUINumberKeyboard *keyboard = [XUINumberKeyboard numberKeyboard];
    keyboard.delegate = parentView;
    [(UIView*)parentView addSubview:keyboard];
    [keyboard setNeedsLayout];
}

+ (void)unloadNumberKeyboardWtihParentView:(id<XUINumberKeyboardDelegate>)parentView
{
    XUINumberKeyboard *keyboard = [XUINumberKeyboard numberKeyboard];
    if(keyboard.superview == (UIView*)parentView)
    {
        keyboard.delegate = nil;
        [keyboard removeFromSuperview];
    }
}

@end

@interface XUINumberKeyboardContain : UIView<XUINumberKeyboardDelegate>
{
    UITextField *_textField;
}

@property(nonatomic,readonly) UITextField *textField;

@end

@implementation XUINumberKeyboardContain

- (id)initWithTextField:(UITextField*)textField
{
    self = [super initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].applicationFrame.size.width, 216)];
    
    self.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    
    self.backgroundColor = [UIColor whiteColor];
    
    _textField = textField;
    
    return self;
}

- (void)dealloc
{
    [XUINumberKeyboard unloadNumberKeyboardWtihParentView:self];
    _textField = nil;
    superdealloc_mm;
}

- (void)willMoveToSuperview:(UIView *)newSuperview
{
    if(newSuperview != nil)
    {
        [XUINumberKeyboard loadNumberKeyboardWtihParentView:self];
        
    }
    else
    {
        [XUINumberKeyboard unloadNumberKeyboardWtihParentView:self];
    }
}

- (UITextField*)textField
{
    return _textField;
}

@end


@interface UITextField (XUINumberKeyboard)

@end

@implementation UITextField (XUINumberKeyboard)

+ (void)load
{
    Method oriMethod = class_getInstanceMethod([self class], @selector(layoutSubviews));
    Method newMethod = class_getInstanceMethod([self class], @selector(thisLayoutSubviews));
    method_exchangeImplementations(oriMethod,newMethod);
}

-(void)thisLayoutSubviews
{
    [self thisLayoutSubviews];
    
    if((NSInteger)self.keyboardType >= XUINumberKeyboardTypeDecimal && self.inputView == nil)
        self.inputView = [[[XUINumberKeyboardContain alloc] initWithTextField:self] autorelease_mm];
}

@end
